(function(angular) {
	'use strict';
	angular.module("fs.waf").factory("reportService", reportService);
	reportService.$inject = [ '$q', 'loggerFactory', 'commonService', 'ajaxServiceFactory', 'modalService', 'gridService', '$filter' ];
	function reportService($q, loggerFactory, commonService, ajaxServiceFactory, modalService, gridService, $filter) {
		var log = loggerFactory.getLogger("reportService"), ajaxService = ajaxServiceFactory.buildAjaxService({
			getReportOptions : {
				url : 'do/cda/dataList/reportOptions',
				method : 'get'
			},
			getReportSortSequence : {
				url : 'do/cda/dataList/reportSortSequence',
				method : 'get'
			}
		});
		
		function getReportOptions() {
			var defer = $q.defer();
			ajaxService.getReportOptions().then(function(response) {
				var reportOptions = {};
				if (response.data) {
					angular.forEach(response.data, function(value, key) {
						var tempValue = {};
						tempValue.data = value;
						reportOptions[key] = tempValue;
					});
				}
				defer.resolve(reportOptions);
			});
			return defer.promise;
		}
		
		function getReportSortSequenceOptions(adrptField) {
			var defer = $q.defer();
			ajaxService.getReportSortSequence(adrptField).then(function(response) {
				defer.resolve(response);
			});
			return defer.promise;
		}
	
		return {
			getReportSortSequenceOptions : getReportSortSequenceOptions,
			getReportFormatsOptions : getReportFormatsOptions,
			initCompany : initCompany,
			initReportParameter : initReportParameter,
			initDataOptions : initDataOptions,
			getReportFormatsExcelOptions : getReportFormatsExcelOptions,
			getReportOptions : getReportOptions
		};
		
		function initDataOptions($scope, ctrl) {
			getReportOptions().then(function(response) {
				ctrl.serviceCodeOptions = response.reportService.data;
				ctrl.reportCategoryOptions = response.reportCategory;
				ctrl.rptenginecodeOptions = response.reportEngine;
			}, angular.noop);
			
			ctrl.reportFormatsOptions = getReportFormatsOptions();
			
			ctrl.changeReportEngine = function(report, formCtrl, isInitialized){
				if(isInitialized){
					return true;
				}
				report.reportFormatList = [];
				if ( report && report.rptEngineCode == "X"){				
					ctrl.reportFormatsOptions = getReportFormatsExcelOptions();
					report.reportFormatList.push("XLS");
				} else {
					ctrl.reportFormatsOptions = getReportFormatsOptions();
					report.reportFormatList.push("PDF");
				}
				
				//for reportOptions
				if( ctrl.report.templateZipped == 'Y'){
					ctrl.reportOptions = getReportZipOptions().data;
					
				}else{
					var rptEngine = report.rptEngineCode;
					if(rptEngine =='J'){
						ctrl.reportOptions = getReportJasperOptions().data;
					}else{
						ctrl.reportOptions = getReportExcelOptions().data;
					}
				}
			};
			
			ctrl.templateZippedChanged = function(report, formCtrl, isInitialized){
				if(isInitialized){
					return true;
				}
				if( report.templateZipped == 'Y'){
					ctrl.reportOptions = getReportZipOptions().data;
					
				}else{
					var rptEngine = report.rptEngineCode;
					if(rptEngine =='J'){
						ctrl.reportOptions = getReportJasperOptions().data;
					}else{
						ctrl.reportOptions = getReportExcelOptions().data;
					}
				}
			}
			
		}
		function initReportParameter($scope, ctrl, layoutConfig) {
			//init companyRpts
			ctrl.reportParameterGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.reportParmsCfg.tableConfigs.table, rowSelectionChanged);
			ctrl.reportParameterGridOptions.data = 'vm.report.reportParms';
			ctrl.reportParameterGridOptions.verifyData = 'vm.reportOld.reportParms';
			function rowSelectionChanged(eventRow, selectedRows) {
				ctrl.selectedParameters = selectedRows;
			}
	
			ctrl.addAdHoc = function() {
				var params = {};
				params.reportAd = ctrl.report.reportAd || {};
				params.reportAd.serviceCode = ctrl.report.serviceCode;
				params.readOnly = ctrl.readOnly;
				modalService.openCustomDialogs({
				   'title': 'title.report.adhoc',
				   'dialogsModule' : 'cda.reportAdHoc',
				   'params' : params,
				   'btnCallback' : {
						'ok' : function(reportAd) {			
							if (!ctrl.report.reportAd) {								
								ctrl.report.reportAd = {};
							}
							ctrl.report.reportAd = reportAd;
						}
					}				   
				});			
			};
		
		}
		function initCompany($scope, ctrl, updateProcessFlag, layoutConfig) {
			//init companyRpts
			ctrl.companyGridOptions = gridService.createInnerGridOptions($scope, layoutConfig.formConfigs.company.tableConfigs.table, rowSelectionCompanyChanged);
			ctrl.companyGridOptions.data = 'vm.report.companyRpts';
			ctrl.companyGridOptions.verifyData = 'vm.reportOld.companyRpts';
			function rowSelectionCompanyChanged(eventRow, selectedRows) {
				ctrl.selectedCompanyRpts = selectedRows;
			}
			
			ctrl.addCompany = function(row) {
				return $q(function(resolved, rejected){
					if (!ctrl.report.serviceCode) {
						modalService.openErrorDialogs({
							messages : [ 'js.info.report.servicecode-required' ]
						});
						return;
					}
					if (!ctrl.report.reportName) {
						modalService.openErrorDialogs({
							messages : [ 'js.info.report.reportname-required' ]
						});
						return;
					}
					
					var params = {};
					params.reportCompanyCodes = [];
					params.reportFormats = ctrl.report.reportFormats;
					params.reportFormatsOptions = getReportFormatsOptions();
					params.partyCode = ctrl.report.companyCode;
					params.companyTypeList = ctrl.report.companyTypes;
					params.serviceCode = ctrl.report.serviceCode;
					params.reportFormatList = ctrl.report.reportFormatList;
					if(ctrl.report.companyRpts){
						angular.forEach(ctrl.report.companyRpts, function(company, index) {
							params.reportCompanyCodes.push($filter('encode')(company.companyCode));
						});
					}
					modalService.openCustomDialogs({
						'dialogsModule' : 'cda.reportCompany',
						'params' : params,
						'btnCallback' : {
							'ok' : function(obj) {
								var selectedRows = obj.selectedRows;
								if (!selectedRows || selectedRows.length == 0) {
									modalService.openErrorDialogs({
										messages : [ 'title.dialogs.info.norecsel' ]
									});
									return false;
								}
								if (!ctrl.report.companyRpts) {
									ctrl.report.companyRpts = [];
								}
								var format = "";
								angular.forEach(obj.reportCompany.reportFormatList, function(reportFormat, index) {
									if(index == obj.reportCompany.reportFormatList.length -1){
										format = format + reportFormat;
									}else{
										format = format + reportFormat+",";
									}
									
								});
								angular.forEach(selectedRows, function(selectedRow, index) {
									selectedRow.dataStatus = 'C';
									selectedRow.reportFormats = format;
									if (updateProcessFlag) {
										selectedRow.isEnabled = "Y";
										selectedRow.archiveMethod = "N";
									}
									ctrl.report.companyRpts.push(selectedRow);
								});
								event.preventDefault();
								event.stopPropagation();
							},
							'close' : function(){
								rejected();
							}
						}
					});
				});
				
			};
		ctrl.viewCompany = function(row) {
			var params = {};
			// for show selected report on popup page
			var _selectedCompanyReport = row.entity;
			params.companyRpt = angular.copy(_selectedCompanyReport);
			params.companyRpt.reportName = ctrl.report.reportName;
			params.companyRpt.serviceCode = ctrl.report.serviceCode;
			params.companyRpt.localeCode = params.companyRpt.localeCode || "en_US";
			if(params.companyRpt.reportParams){
				params.companyRpt.reportParms = JSON.parse(params.companyRpt.reportParams); 
			}
			if(params.companyRpt.reportFormats){
				params.companyRpt.reportFormatList = [];
				var fieldArr = params.companyRpt.reportFormats.split(",");
				for(var i = 0; i < fieldArr.length; i++){
					if(fieldArr[i] != ""){
						params.companyRpt.reportFormatList.push(fieldArr[i]);
					}
				}
			}
			modalService.openCustomDialogs({
			   'title': 'title.report.company',
			   'dialogsModule' : 'cda.reportCompanyView',
			   'params': params
			    
			});	
		  };
			ctrl.editCompany = function(row) {
				var params = {};
				// for show selected report on popup page
			    var _selectedCompanyReport = row.entity;
				params.companyRpt = angular.copy(_selectedCompanyReport); 
				params.companyRpt.reportName = ctrl.report.reportName;
				params.companyRpt.serviceCode = ctrl.report.serviceCode;
				if(!_selectedCompanyReport.isEnabled){
					_selectedCompanyReport.isEnabled = ctrl.report.isEnabled;
				}
				params.companyRpt.isEnabled = _selectedCompanyReport.isEnabled;
				params.companyRpt.localeCode = params.companyRpt.localeCode || "en_US";
				if(!_selectedCompanyReport.archiveMethod){
					_selectedCompanyReport.archiveMethod = ctrl.report.archiveMethod;
				}
				params.companyRpt.archiveMethod = _selectedCompanyReport.archiveMethod;
				if(params.companyRpt.reportParams){
					params.companyRpt.reportParms = JSON.parse(params.companyRpt.reportParams);
				}
				if(params.companyRpt.reportFormats){
					params.companyRpt.reportFormatList = [];
					var fieldArr = params.companyRpt.reportFormats.split(",");
					for(var i = 0; i < fieldArr.length; i++){
						if(fieldArr[i] != ""){
							params.companyRpt.reportFormatList.push(fieldArr[i]);
						}
					}
				}
				modalService.openCustomDialogs({
				   'title': 'title.report.company',
				   'dialogsModule' : 'cda.reportCompanyEdit',
				   'params':  params,
				   'btnCallback' : {
						'ok' : function(report) {			
							if (!ctrl.report.companyRpts) {								
								ctrl.report.companyRpts = [];
							}
							if (!(report.dataStatus == 'C' || report.dataStatus == 'U')) {
								if (updateProcessFlag) {
									report.dataStatus = 'U';
								} else {
									report.dataStatus = 'C';
								}
							}
							angular.extend(_selectedCompanyReport, report);
							var format = "";
							angular.forEach(report.reportFormatList, function(reportFormat, index) {
								if(index == report.reportFormatList.length -1){
									format = format + reportFormat;
								}else{
									format = format + reportFormat+",";
								}
								
							});
							_selectedCompanyReport.reportFormats = format;
						}
					}				   
				});	
			};
			
		}

		function getReportZipOptions(){
			return {
				"data" : [ {
					"label" : "ZIP",
					"value" : "application/x-zip-compressed"
				}]
			};
		}
		function getReportExcelOptions(){
			return {
				"data" : [ {
					"label" : "EXCEL",
					"value" : "application/vnd.ms-excel,application/x-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
				}]
			};
		}
		function getReportJasperOptions(){
			return {
				"data" : [ {
					"label" : "JASPER",
					"value" : "application/jasper"
				}]
			};
		}
		
		function getReportFormatsOptions() {
			return {
				"data" : [ {
					"label" : "PDF",
					"value" : "PDF"
				},{
					"label" : "XLS",
					"value" : "XLS"
				},{
					"label" : "CSV",
					"value" : "CSV"
				},{
					"label" : "HTML",
					"value" : "HTML"
				}]
			};
		}
		function getReportFormatsExcelOptions() {
			return {
				"data" : [ {
					"label" : "XLS",
					"value" : "XLS"
				}]
			};
		}
	}
})(angular);